package net.topicopedia.other;
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

@SuppressWarnings("serial")
public class GetTopicServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		
		resp.addHeader("Access-Control-Allow-Origin", "*");
		resp.setContentType("text/plain");
		
		String output = "";
		
		String uuid = (String) req.getParameter("topic");
		Key topicKey = KeyFactory.createKey("Topic", (Long) Long.parseLong(uuid) );
		
		if ( topicKey == null  )
		{
			output = "{}";
			resp.getWriter().println( output );
			return;
		}
		
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		
		Entity topic = null;
		try {
			topic = datastore.get( topicKey );
		} catch (EntityNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		if ( topic == null )
		{
			output = "{}";
			resp.getWriter().println( output );
			return;
		}
		
		String storedUuid = topic.getKey().getId() + "";
		String storedTitle = (String) topic.getProperty("title");
		String storedDescriptor = (String) topic.getProperty("descriptor");
		String storedCategory = topic.getProperty("category")+"";
		@SuppressWarnings("unchecked")
		List<String> storedTagsList = (List<String>) topic.getProperty("tags");
		String storedTags="";
		for ( int t=0; t< storedTagsList.size(); t++)
		{
			String storedTag = storedTagsList.get(t);
			if ( storedTag != null )
			{
				if ( t > 0 )
				{
					storedTags += ", ";
				}
				storedTags += storedTag;
			}
		}
		String storedItems = (String)  topic.getProperty("items");
		String storedLinks = (String) topic.getProperty("links");
		
		
		output += "{\"uuid\": " + storedUuid;
		output += ", \"title\": " + "\"" + storedTitle + "\"";
		output += ", \"descriptor\": " + "\"" + storedDescriptor + "\"";
		output += ", \"category\": " + storedCategory;
		output += ", \"tags\": " + "\"" + storedTags + "\"";
		output += ", \"items\": " + storedItems;
		output += ", \"links\": " + storedLinks;
		output += "}";
		
		resp.getWriter().println( output );
		
	}
}
 